import express, { Request, Response } from "express";
import sequelize from "./config/db";
import dotenv from "dotenv";
import cors from "cors";
import bodyParser from "body-parser";
import userRoutes from "./routes/users";
import authRoutes from "./routes/auth";
import roleRoutes from "./routes/roles";
import uploadsRoutes from "./routes/uploads";
import articlesRoutes from "./routes/articles";
import categoriesRoutes from "./routes/categories";
import tagsRoutes from "./routes/tags";

import { responseMiddleware } from "@/middleware/response";
import { checkToken } from "@/middleware/tokenCheck";
import path from "path";

// 加载环境变量
dotenv.config();

// 创建 Express 应用
const app = express();
// 静态文件托管
app.use(
  "/uploads",
  express.static("uploads", {
    maxAge: 0, // 禁用缓存
    etag: false, // 禁用 ETag
  })
);
// 中间件
app.use(cors()); // 移除接口跨域
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(responseMiddleware); // 处理响应数据
app.use(checkToken); // 处理响应数据

// 同步数据库
sequelize
  .sync({ force: false }) // 设置为 true 会删除现有表，谨慎使用
  .then(() => {
    console.log("Database synced");
  })
  .catch((err) => {
    console.error("Error syncing database:", err);
  });

// 管理后台路由
app.use("/admin-api/auth", authRoutes);
// 用户接口
app.use("/admin-api/users", userRoutes);
// 文件上传接口
app.use("/admin-api/upload", uploadsRoutes);
// 文章接口
app.use("/admin-api/articles", articlesRoutes);
// 文章分类接口
app.use("/admin-api/categories", categoriesRoutes);
// 标签接口
app.use("/admin-api/tags", tagsRoutes);
// app.use('/api/roles', roleRoutes);categories

// 启动服务
const PORT = Number(process.env.PORT) || 3000;
app.listen(PORT, "0.0.0.0", () => {
  console.log(`Server running on port ${PORT}`);
});
